import { defineStore } from 'pinia'
import axios from 'axios'

export const useBpmnStore = defineStore('bpmn', {
    state: () => ({
        diagramXML: '',
        selectedElement: null,
        elements: [],
        listeners: [],
        backendUrl: 'http://your-api-endpoint/processes',
        bpmnModeler: null  // 添加模型实例引用
    }),
    actions: {
        async loadInitialDiagram() {
            try {
                const response = await axios.get('@/assets/initial.bpmn')
                this.diagramXML = response.data
                return response.data
            } catch (error) {
                console.error('加载初始流程图失败:', error)
                return null
            }
        },
        async saveDiagramToBackend(xmlData) {
            try {
                const response = await axios.post(this.backendUrl, {
                    xml: xmlData
                })
                return response.data
            } catch (error) {
                console.error('保存到后端失败:', error)
                throw error
            }
        },
        addListener(listener) {
            this.listeners.push(listener)
            this.updateElementListeners()
        },
        updateElementListeners() {
            if (this.selectedElement && this.bpmnModeler) {
                const modeling = this.bpmnModeler.get('modeling')
                modeling.updateProperties(this.selectedElement, {
                    listeners: this.listeners
                })
            }
        },
        setSelectedElement(element) {
            this.selectedElement = element
            if (element) {
                this.listeners = element.businessObject.listeners || []
            }
        },
        // 新增：设置模型实例
        setModeler(modeler) {
            this.bpmnModeler = modeler
        }
    }
})